package com.liugh.asyn;

import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 用于异步执行任务的service
 */
public class AsyncJobManager {
    /**
     * 单例
     */
    private static AsyncJobManager sInstance;

    private AsyncJobManager() {}

    /**
     * 获取单例
     * @return
     */
    public static AsyncJobManager getInstance() {
        if (null == sInstance) {
            synchronized (AsyncJobManager.class) {
                if (null == sInstance) {
                    sInstance = new AsyncJobManager();
                }
            }
        }
        return sInstance;
    }

    private HashMap<String, ExecutorService> mThreadPool = new HashMap<>();


    /**
     * 添加并开始执行一个任务
     * @param job
     */
    public synchronized void addJob(AsyncJob job) {
        ExecutorService threadPool = mThreadPool.get(job.getQueue());

        if (null == threadPool) {
//            threadPool = Executors.newCachedThreadPool();
            threadPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                    60L, TimeUnit.SECONDS,
                    new PriorityBlockingQueue<>());  // 按照优先级进行排序
            mThreadPool.put(job.getQueue(), threadPool);
        }

        threadPool.execute(job);
    }







}
